package cug.example.learningbase.utils;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;

/**
 * @BelongsProject: hexy-job-modules
 * @BelongsPackage: cug.example.learningbase.utils
 * @Author: halu
 * @CreateTime: 2025-09-23 19:16
 * @Description: TODO
 * @Version: 1.0
 **/
public class FileReaderUtil {

    /**
     * @description: 一次型读取文件到内存 适合小文件 ,大文件会出现java.lang.OutOfMemoryError（内存溢出）问题
     * @author: halu
     * @date: 2025/9/23 19:18
     * @param: [filePath]
     * @return: java.lang.String
     **/
    public static String readSmallFile(String filePath) throws IOException {
        StringBuilder contenBuilder = new StringBuilder();
        List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
        for(String line : lines){
            contenBuilder.append(line).append("\n");
        }
        return contenBuilder.toString();
        // 其他方法：java 11 开始提供的方法，读取文件不能超过2G，与你的内存息息相关
//        return Files.readString(Paths.get(filePath));
    }

    /**
     * @description: 逐行读取文件 适合大文件（管道流）
     * @author: halu
     * @date: 2025/9/23 19:18
     * @param: [filePath]
     * @return: java.lang.String
     **/
    public static String readBigFile(String filePath) throws IOException {
        StringBuilder contenBuilder = new StringBuilder();
        try(BufferedReader reader = new BufferedReader(new FileReader(filePath))){
            String line;
            while((line = reader.readLine()) != null){
                contenBuilder.append(line).append("\n");
            }
        }
        return contenBuilder.toString();
    }

    /**
     * @description: 流式处理
     * @author: halu
     * @date: 2025/9/23 19:37
     * @param:
     * @return:
     **/
    public static String streamHandleFile(String filePath) throws IOException {
        StringBuilder contenBuilder = new StringBuilder();
        // 读取文件内容到Stream流中，按行读取
        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            lines.forEach(line -> contenBuilder.append(line).append("\n"));
        }
       return contenBuilder.toString();
    }

}
